package com.zhen.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhen.mapper.DataBatchInsertCustomMapper;
import com.zhen.service.DataBatchInsertCustomService;
@Service
@Transactional
public class DataBatchInsertCustomServiceImpl implements DataBatchInsertCustomService{

	@Autowired
	private DataBatchInsertCustomMapper pojoRepository;
	
	@Override
	public int insertByBatchReturnCountHistory(List<Map<String, Object>> updateItems, String dbName, String tableName, String[] exceptColArr) throws Exception {

		int resultCount = 0;
		try {
			resultCount = 0;
			if (!updateItems.isEmpty()) {
				Map<String, Object> params = new HashMap<String, Object>();
				// 这里将数据分成每X条执行一次，可根据实际情况调整
				int batchSize = 100;
				int count = updateItems.size() / batchSize;
				int yu = updateItems.size() % batchSize;
				for (int i = 0; i <= count; i++) {
					List<Map<String, Object>> subList = null;
					if (i == count) {
						if (yu != 0) {
							subList = updateItems.subList(i * batchSize, batchSize * i + yu);
						} else {
							continue;
						}
					} else {
						subList = updateItems.subList(i * batchSize, batchSize * (i + 1));
					}
					if(StringUtils.isNotBlank(dbName)){
						
						params.put("table_name", String.format("%s.%s", dbName, tableName));
					}else{
						
						params.put("table_name", tableName);
					}
					params.put("fields", subList.get(0));
					params.put("list", subList);
					pojoRepository.insertByBatch(params);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultCount;
	}
}
